% ---------------------------------------------------
% @doc 用户信息处理器.
% ---------------------------------------------------
-module(cloap_rest).
-include("cloap_record.hrl").

-export([init/2]).
-export([
         allowed_methods/2,
         content_types_provided/2,
         content_types_accepted/2,
         resource_exists/2,
         delete_resource/2
        ]).

-export([
         event/2, handle/3
        ]).


init(Req, Opts) ->
    {cowboy_rest, Req, Opts}.

event(Req, State) ->
    Paths   = cowboy_req:path_info(Req),
    Method  = binary_to_list(cowboy_req:method(Req)),
    Body = 
        try
            {ok, [{Body1,true}], _Req} = cowboy_req:body_qs(Req),
            Body1
        catch
            _:_ -> []
        end,


    Result = jsx:encode(handle(Method, Paths, Body)),

    case Method of
        "GET" ->
            {Result, Req, State};
        "DELETE" ->
            {Result, Req, State};
        "POST" ->
            Req1 = cowboy_req:set_resp_body(Result, Req),
            {true, Req1, State}
    end.

handle("GET", [<<"action_log">>], []) ->
    cloap_log:search([]);
handle("GET", [<<"action_log">>, AppId], []) ->
    cloap_log:search([AppId]);
handle(Method, Argv, _) ->
    lager:error("~p ~p", [Method, Argv]).
            



allowed_methods(Req, State) ->
  {
    [<<"GET">>, <<"POST">>, <<"HEAD">>, <<"DELETE">>, <<"OPTIONS">>],
    Req, State
  }.


content_types_provided(Req, State) ->
    Req1 = cowboy_req:set_resp_header(<<"access-control-allow-methods">>, <<"GET, POST, DELETE, HEAD, OPTIONS">>, Req),
    Req2 = cowboy_req:set_resp_header(<<"access-control-allow-origin">>, <<"*">>, Req1),
    {[
      {<<"text/plain;charset=utf-8">>, event},
      {<<"application/json">>, event}
     ], Req2, State}.

content_types_accepted(Req, State) ->
    {[
      {<<"text/plain;charset=utf-8">>, event},
      {<<"application/json">>, event}
     ],
     Req, State}.


resource_exists(Req, State) ->
    {true, Req, State}.

delete_resource(Req, State) ->
    {Result, _, _} = event(Req, State),
    Req1 = cowboy_req:set_resp_body(Result, Req),
    {true, Req1, State}.

